<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\ChangePasswordRequest;
use App\Http\Requests\AdminCreateRequest;
use App\Http\Requests\AdminUpdateRequest;
use App\Models\Admin;
use App\Models\Configuration;
use App\Models\LoginLog;
use Illuminate\Contracts\Auth\StatefulGuard;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Routing\Redirector;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\View;
use App\Models\Role;
use App\Models\Permission;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Storage;
use zgldh\QiniuStorage\QiniuStorage;

/***************后台管理员控制器********************/
class AdminController extends Controller
{

    use AuthenticatesUsers;

    /*public function __construct()
    {
        $this->middleware('auth:admin');
    }*/

    /**
     * 登录表单
     * @return \Illuminate\Contracts\View\View
     */
    public function showLoginForm()
    {
        return View::make('admin.admin.login');
    }

    /**
     * 验证登录字段
     * @param Request $request
     * @throws ValidationException
     */
    protected function validateLogin(Request $request)
    {
        $this->validate($request, [
            'captcha' => 'required|captcha',
            $this->username() => 'required|string',
            'password' => 'required|string',
        ]);
    }

    //登录成功后的跳转地址
    public function redirectTo()
    {
        return URL::route('admin.layout');
    }

    /**
     * 退出后的动作
     * @param Request $request
     * @return RedirectResponse|Redirector
     */
    protected function loggedOut(Request $request)
    {
        return Redirect::to(URL::route('admin.login'));
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard('admin');
    }

    protected function authenticated(Request $request, $admin)
    {
        //缓存配置信息
        $configuration = Configuration::pluck('val','key');
        $request->session()->put('configuration',$configuration);
        //记录登录成功日志
        if ($configuration['login_log']==1){
            LoginLog::create([
                'username' => $admin->username,
                'ip' => $request->ip(),
                'method' => $request->method(),
                'user_agent' => $request->header('User-Agent'),
                'remark' => '登录成功',
            ]);
        }
    }

    /**
     * 用于登录的字段
     * @return string
     */
    public function username()
    {
        return 'username';
    }

    /**
     * 更改密码
     * @return \Illuminate\Contracts\View\View
     */
    public function changeMyPasswordForm()
    {
        return View::make('admin.admin.changeMyPassword');
    }

    /**
     * 修改密码
     * @param ChangePasswordRequest $request
     * @return RedirectResponse
     */
    public function changeMyPassword(ChangePasswordRequest $request)
    {
        $data = $request->all(['old_password','new_password']);
        //验证原密码
        if (!Hash::check($data['old_password'],$request->user()->getAuthPassword())){
            return Redirect::back()->withErrors('原密码不正确');
        }
        try{
            $request->user()->fill(['password' => $data['new_password']])->save();
            return Redirect::back()->with(['success'=>'密码修改成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('修改失败');
        }
    }

    /**
     * 管理员列表主页
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        return View::make('admin.admin.index');
    }

    //返回管理员数据
    public function data(Request $request)
    {
        $res = Admin::paginate($request->get('limit', 30));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items()
        ];
        return Response::json($data);
    }

    /**
     * 添加管理员
     * @return \Illuminate\Contracts\View\View
     */
    public function create()
    {
        return View::make('admin.admin.create');
    }

    /**
     * 保存管理员
     * @param AdminCreateRequest $request
     * @return RedirectResponse
     */
    public function store(AdminCreateRequest $request)
    {
        $data = $request->all();
        try{
            Admin::create($data);
            return Redirect::to(URL::route('admin'))->with(['success'=>'添加成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return void
     */
    public function show($id)
    {
        //
    }

    /**
     * 编辑管理员
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit($id)
    {
        $admin = Admin::findOrFail($id);
        return View::make('admin.admin.edit',compact('admin'));
    }

    /**
     * 更新管理员
     * @param AdminUpdateRequest $request
     * @param $id
     * @return RedirectResponse
     */
    public function update(AdminUpdateRequest $request, $id)
    {
        $admin = Admin::findOrFail($id);
        $data = $request->except('password');
        if ($request->get('password')){
            $data['password'] = $request->get('password');
        }
        try{
            $admin->update($data);
            return Redirect::to(URL::route('admin'))->with(['success'=>'更新成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('更新失败');
        }
    }

    /**
     * 删除管理员
     * @param Request $request
     * @return JsonResponse
     */
    public function destroy(Request $request)
    {
        $ids = $request->get('ids');
        if (!is_array($ids) || empty($ids)){
            return Response::json(['code'=>1,'msg'=>'请选择删除项']);
        }
        try{
            Admin::destroy($ids);
            return Response::json(['code'=>0,'msg'=>'删除成功']);
        }catch (\Exception $exception){
            return Response::json(['code'=>1,'msg'=>'删除失败']);
        }
    }

    /**
     * 分配角色页面
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function role($id)
    {
        $admin = Admin::findOrFail($id);
        $roles = Role::get();
        foreach ($roles as $role){
            $role->own = $admin->hasRole($role) ? true : false;
        }
        return View::make('admin.admin.role',compact('roles','admin'));
    }

    /**
     * 执行分配角色
     * @param Request $request
     * @param $id
     * @return RedirectResponse
     */
    public function assignRole(Request $request,$id)
    {
        $admin = Admin::findOrFail($id);
        $roles = $request->get('roles',[]);
        try{
            $admin->syncRoles($roles);
            return Redirect::to(URL::route('admin'))->with(['success'=>'更新成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('更新失败');
        }
    }

    /**
     * 分配直接权限
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function permission($id)
    {
        $admin = Admin::findOrFail($id);
        $permissions = Permission::with('allChilds')->where('parent_id',0)->get();
        foreach ($permissions as $p1){
            $p1->own = $admin->hasDirectPermission($p1->id) ? 'checked' : '' ;
            if ($p1->childs->isNotEmpty()){
                foreach ($p1->childs as $p2){
                    $p2->own = $admin->hasDirectPermission($p2->id) ? 'checked' : '' ;
                    if ($p2->childs->isNotEmpty()){
                        foreach ($p2->childs as $p3){
                            $p3->own = $admin->hasDirectPermission($p3->id) ? 'checked' : '' ;
                        }
                    }
                }
            }
        }
        return View::make('admin.admin.permission',compact('admin','permissions'));
    }

    /**
     * 分配直接权限
     * @param Request $request
     * @param $id
     * @return RedirectResponse
     */
    public function assignPermission(Request $request,$id)
    {
        $admin = Admin::findOrFail($id);
        $permissions = $request->get('permissions',[]);
        try{
            $admin->syncPermissions($permissions);
            return Redirect::to(URL::route('admin'))->with(['success'=>'更新成功']);
        }catch (\Exception $exception){
            return Redirect::back()->withErrors('更新失败');
        }
    }
//单图片上传
    public function uploadEditor(Request $request)
    {
        //上传文件最大大小,单位M
        $maxSize = 5;
        //支持的上传图片类型
        $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
        //返回信息json
        $data = ['code'=>1, 'msg'=>'上传失败', 'data'=>''];
        $file = $request->file('file');

        //检查文件是否上传完成
        if ($file->isValid()){
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext),$allowed_extensions)){
                $data['msg'] = "请上传".implode(",",$allowed_extensions)."格式的图片";
                return response()->json($data);
            }
            //检测图片大小
            if ($file->getSize() > $maxSize*1024*1024){
                $data['msg'] = "图片大小限制".$maxSize."M";
                return response()->json($data);
            }
        }else{
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }
        $newFile = date('Y-m-d')."_".time()."_".uniqid().".".$file->getClientOriginalExtension();
        $disk = QiniuStorage::disk('qiniu');

        $res = $disk->put($newFile,file_get_contents($file->getRealPath()));
        if($res){
            $data = [
                'errno'  => 0,
                'data' =>[
                    'href'   => $newFile,
                    'alt'  => $newFile,
                    'url'   => $disk->downloadUrl($newFile)
                ]
            ];
        }else{
            $data = [
                'errno'  => 1,
                'message' =>'failed'
            ];
        }
        return response()->json($data);
    }


    //单图片上传
    public function upload(Request $request)
    {
        //上传文件最大大小,单位M
        $maxSize = 5;
        //支持的上传图片类型
        $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
        //返回信息json
        $data = ['code'=>1, 'msg'=>'上传失败', 'data'=>''];
        $file = $request->file('file');

        //检查文件是否上传完成
        if ($file->isValid()){
            //检测图片类型
            $ext = $file->getClientOriginalExtension();
            if (!in_array(strtolower($ext),$allowed_extensions)){
                $data['msg'] = "请上传".implode(",",$allowed_extensions)."格式的图片";
                return response()->json($data);
            }
            //检测图片大小
            if ($file->getSize() > $maxSize*1024*1024){
                $data['msg'] = "图片大小限制".$maxSize."M";
                return response()->json($data);
            }
        }else{
            $data['msg'] = $file->getErrorMessage();
            return response()->json($data);
        }
        $newFile = date('Y-m-d')."_".time()."_".uniqid().".".$file->getClientOriginalExtension();
        $disk = QiniuStorage::disk('qiniu');
       /* $res = $disk->put($newFile,file_get_contents($file->getRealPath()));
        if($res){
            $data = [
                'code'  => 0,
                'msg'   => '上传成功',
                'data'  => $newFile,
                'url'   => config('app.asset_url') . '/uploads/local/'.$newFile,
            ];
        }else{
            $data['data'] = $file->getErrorMessage();
        }*/
        $res = $disk->put($newFile,file_get_contents($file->getRealPath()));
        if($res){
            $data = [
                'code'  => 0,
                'msg'   => '上传成功',
                'data'  => $newFile,
                'url'   => $disk->downloadUrl($newFile)
            ];
        }else{
            $data['data'] = $file->getErrorMessage();
        }
        return response()->json($data);
    }

}
